//
//  NetTools.swift
//  AFN网络工具类
//
//  Created by mac on 16/4/17.
//  Copyright © 2016年 it.cast. All rights reserved.
//

import UIKit

import AFNetworking

/// 请求的枚举
enum CZRequestMethod: String{
    
    case GET = "GET"
    
    case POST = "POST"
}


class NetTools: AFHTTPSessionManager {
    
    /// 应用程序的信息
    private let appKey = "2218387540"
    private let appSecret = "8b8f35d2d1ee8ab07052eb141d9c46f2"
    private let redirectUrl = "http://www.baidu.com"
    
    //定义别名，方便书写,重要的方法放在上面
    typealias CZRequestCallBack = (result: AnyObject?, error:NSError?)->()
    
    static let shareTools:NetTools = {
        
        let tools = NetTools(baseURL: nil)
        
        //设置解析的类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        return tools
        
    }()

}

///加载授权方法 拿到code
extension NetTools{
    
    var OAthth:NSURL {
        
        //https://api.weibo.com/oauth2/authorize?client_id=2218387540&redirect_uri=http://www.baidu.com
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
    }
    
    //加载access页面
    func loadAccessToken(code: String,finished:CZRequestCallBack){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id":appKey,"client_secret":appSecret,
            "grant_type":"authorization_code","code":code,"redirect_uri":redirectUrl]
        
        //afn默认堆json进行了反序列化
        request(.POST, urlString: urlString, parameters: params, finished: finished)
   
    }
}

/// 封装网络工具类
extension NetTools{
    
    //适应token 进行网络请求
    private func tokenRequest(method:CZRequestMethod, urlString: String,var parameters:[String: AnyObject]? ,finished:CZRequestCallBack){
        
        guard let token = CZUserAccountViewModel.shareModel.access_token else {
            
            //错误的回调，自定义错误信息  token为nil
            finished(result: nil, error: NSError(domain: "it.cast", code: -1005, userInfo: ["message":"用户信息不能为空"]))
            
            return
            
        }
        
        // 1 获取token
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
         parameters!["access_token"] = token
        
        // 2 发起网络请求
        request(method, urlString: urlString, parameters: parameters, finished: finished)
    }
    
    
    
    /// 结果都是可选项的，可以不是实现，要用？ 表示，因为他们两个参数一次只会有一个输出来。
    private func request(method:CZRequestMethod, urlString: String,parameters:[String: AnyObject]? ,finished:CZRequestCallBack){
        
        /// 闭包中
        let success = { (task:NSURLSessionDataTask, result:AnyObject?) -> Void in
            
             finished(result: result, error: nil)
        
        }
        
        let failure = { (task:NSURLSessionDataTask?, error:NSError) -> Void in
            
            print(error)
            finished(result: nil, error: error)
        }

        if method == CZRequestMethod.GET{
            GET(urlString, parameters: parameters, success: success, failure: failure)
        }
        else{
            POST(urlString, parameters: parameters, success: success, failure: failure)
        }
      
    }
}

// MARK: 用户相关的信息 姓名，昵称，爱好。。。
extension NetTools{
    
    
  //- see:[https://api.weibo.com/2/place/users/show.json](https://api.weibo.com/2/place/users/show.json)
    func loadUserInfo(uid:String,finished:CZRequestCallBack){
        
        let urlString = "https://api.weibo.com/2/users/show.json"

        var params = [String: AnyObject]()
        
        params["uid"] = uid
        
        tokenRequest(CZRequestMethod.GET, urlString: urlString, parameters: params, finished: finished)
        
    }
}


// MARK: 获取微博的数据 个人的数据
extension NetTools{
   
    // - see:[https://api.weibo.com/2/statuses/home_timeline.json](https://api.weibo.com/2/statuses/home_timeline.json)
    
//    since_id	false	int64	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
//    max_id	false	int64	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    
    func loadStatus(since_id since_id:Int, max_id: Int, finished:CZRequestCallBack){
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"

        var params = [String: AnyObject]()
        
        if since_id > 0 {
            params["since_id"] = since_id;
        }else if max_id > 0 {
            params["max_id"] = max_id - 1;
        }
        
        
        tokenRequest(CZRequestMethod.GET, urlString: urlString, parameters: params, finished: finished)
    }
}


// MARK: 发送一条微博
extension NetTools{
    
    func sendStatus(status:String,image:UIImage?, finished:CZRequestCallBack){
        
        
        
        let urlString = "https://api.weibo.com/2/statuses/update.json"

         var params = [String: AnyObject]()
        
        params["status"] = status
        
        if image == nil{
             tokenRequest(CZRequestMethod.POST, urlString: urlString, parameters: params, finished: finished)
        }else{
            
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            let data = UIImagePNGRepresentation(image!)
            
            uploadImage(urlString, data: data!, name: "pic", parameters: params, finished: finished)
        }

    }
    
    //上传照片
    func uploadImage(urlString: String,data: NSData,name:String, var parameters:[String: AnyObject]? ,finished:CZRequestCallBack){

        //拿到token
        
        guard let token = CZUserAccountViewModel.shareModel.access_token else {
            
            //错误的回调，自定义错误信息  token为nil
            finished(result: nil, error: NSError(domain: "it.cast", code: -1005, userInfo: ["message":"用户信息不能为空"]))
            
            return
            
        }
        
        // 1 获取token
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        parameters!["access_token"] = token
        
        
        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            
            //拼接  data 图片的二进制 name服务器定义文件的字段
            formData.appendPartWithFileData(data, name: name, fileName: "xxx", mimeType: "application/octet-stream")
            
            }, progress: nil, success: { (_, result) -> Void in
                finished(result: result, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
        
        
    }

}










